
define(['ionic', 'controllers'], function () {
    angular.module('U9Mobile.controllers')
        .controller('ConnectCtrl', ['$scope', 'ConnectService', 'UserService', 'UtilService',
            function ($scope, ConnectService, UserService, UtilService) {
                $scope.data = {
                    address: '',
                    port: ''
                };

                $scope.$on('$ionicView.beforeEnter', function () {
                    $scope.data.address = ConnectService.getConnect('address');
                    $scope.data.port = ConnectService.getConnect('port');
                });

                $scope.save = function (invalid) {
                    if (invalid) {
                        UtilService.tipsBottom('请输入服务器或端口号');
                        return;
                    }
                    ConnectService.getCompanyList($scope.data.address, $scope.data.port, true).then(function (enterprises) {
                        if (enterprises.length === 0) {
                            UtilService.tipsBottom('未找到公司信息');
                        } else {
                            $scope.appData.orgList = [];
                            UserService.setOrg({});
                            ConnectService.setConnect(
                                $scope.data.address, $scope.data.port, enterprises[0].id
                            ).then(function () {
                                UtilService.goState('app.login');
                            });
                        }
                    }, function () {
                        UtilService.tipsBottom('尝试连接服务器失败，请检查配置是否正确或者网络连接情况然后重试', true);
                    });
                };
            }
        ]);
});